package Java7_Concurrency_Cookbook.concurrent_collection_framework.priority_blocking_queue;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * 当插入元素时, PriorityBlockingQueue使用compareTo()方法来决定插入元素的位置.
 * 元素越大越靠后<br/>
 * PriorityBlockingQueue.clear() 移除队列中所有元素<br/>
 * PriorityBlockingQueue.take() 返回元素并删除, 如果队列为空, 线程将阻塞<br/>
 * PriorityBlockingQueue.put(E e) 元素插入<br/>
 * PriorityBlockingQueue.peek() 返回元素, 但不将其删除
 * @author lixiangke
 * @date 2017/11/23
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        PriorityBlockingQueue<Event> queue = new PriorityBlockingQueue<>();
        Thread[] taskThreads = new Thread[5];
        for (int i = 0; i < taskThreads.length; i++) {
            Task task = new Task(i, queue);
            taskThreads[i] = new Thread(task);
        }
        for (int i = 0; i < taskThreads.length; i++) {
            taskThreads[i].start();
        }
        for (int i = 0; i < taskThreads.length; i++) {
            taskThreads[i].join();
        }
        System.out.printf("Main: Queue Size: %d.\n", queue.size());

        for (int i = 0; i < taskThreads.length * 1000; i++) {
            Event event = queue.poll();
            System.out.printf("Thread: %s: Priority %d\n", event.getThread(), event.getPriority());
        }
        System.out.printf("Main: Queue size: %d\n", queue.size());
        System.out.println("Main: End of the program.");
    }
}
